#! /usr/bin/python
# -*- coding: utf-8 -*-

from google.appengine.ext import db
import conf
import utils

#some configuration value
titleMinLen = 3
titleMaxLen = 64
contentMinLen = 3
contentMaxLen = 40000

#some Constants
paperStatusNormal = 0
paperStatusDeleted = 1
paperStatusDraft = 2
paperStatusProhibited = 3


class Paper(db.Model):
    pid = db.IntegerProperty()
    category = db.StringProperty(multiline=False)
    title = db.StringProperty(multiline=False)
    content = db.TextProperty()
    authorId = db.IntegerProperty()
    createdTime = db.DateTimeProperty(auto_now_add=True)
    lastModifiedTime = db.DateTimeProperty(auto_now=True)
    status = db.IntegerProperty()

#Return the Paper DB Model
def readPaperById(paperId):
    q = db.GqlQuery("SELECT * FROM Paper WHERE pid = :pid and status in (:status1, :status2)", pid=paperId, status1=paperStatusNormal, status2=paperStatusDraft)
    paperModel = q.get()
    if paperModel:
        paperModel.lastModifiedTimeInLocalTimezone = utils.calculateLocalTime(paperModel.lastModifiedTime)
    return paperModel

def writePaper(paperModel):
    paperModel.put()

#Return a list of Paper DB Models for a certain author
def listPapersByAuthor(authorId, offset=0, limit=100, includingDraft=False):
    if includingDraft:
        gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE authorId = :authorId and status in (:status1, :status2) ORDER BY lastModifiedTime DESC", authorId=authorId, status1=paperStatusNormal, status2=paperStatusDraft)
    else:
        gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE authorId = :authorId and status in (:status1, :status2) ORDER BY lastModifiedTime DESC", authorId=authorId, status1=paperStatusNormal, status2=paperStatusNormal)
    resultList = gplQuery.fetch(limit, offset)
    return calculateLocalTimePaperList(resultList)

#Return a list of Paper DB Models for a certain author and category
def listPapersByAuthorCategory(authorId, category, offset=0, limit=100, includingDraft=False):
    if includingDraft:
        gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE authorId = :authorId and category=:category and status in (:status1, :status2) ORDER BY lastModifiedTime DESC", authorId=authorId, category=category, status1=paperStatusNormal, status2=paperStatusDraft)
    else:
        gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE authorId = :authorId and category=:category and status in (:status1, :status2) ORDER BY lastModifiedTime DESC", authorId=authorId, category=category, status1=paperStatusNormal, status2=paperStatusNormal)
    resultList = gplQuery.fetch(limit, offset)
    return calculateLocalTimePaperList(resultList)

def listAllPapers(offset=0, limit=100):
    gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE status in (:status1, :status2) ORDER BY lastModifiedTime DESC", status1=paperStatusNormal, status2=paperStatusNormal)
    resultList = gplQuery.fetch(limit, offset)
    return calculateLocalTimePaperList(resultList)

def listPapersByCategory(category, offset=0, limit=100):
    gplQuery = db.GqlQuery("SELECT * FROM Paper WHERE category=:category and status in (:status1, :status2) ORDER BY lastModifiedTime DESC", category=category, status1=paperStatusNormal, status2=paperStatusNormal)
    resultList = gplQuery.fetch(limit, offset)
    return calculateLocalTimePaperList(resultList)

#def convertGplQuery2List(qplQuery):
#    paperList = []
#    for paperModel in qplQuery:
#        paperMap = {
#            'pid': paperModel.pid,
#            'category': paperModel.category,
#            'title': paperModel.title,
#            'content': paperModel.content,
#            'authorId': paperModel.authorId,
#            'createdTime': paperModel.createdTime,
#            'lastModifiedTime': paperModel.lastModifiedTime,
#            'lastModifiedTimeInLocalTimezone': '%04d-%02d-%02d %02d:%02d' % 
#                (paperModel.lastModifiedTime.year, paperModel.lastModifiedTime.month, 
#                 paperModel.lastModifiedTime.day, (paperModel.lastModifiedTime.hour + 8) % 24, 
#                 paperModel.lastModifiedTime.minute)
#        }
#        paperList.append(paperMap)
#    return paperList

def  calculateLocalTimePaperList(queryResultList):
    for paperModel in queryResultList:
        paperModel.lastModifiedTimeInLocalTimezone = utils.calculateLocalTime(paperModel.lastModifiedTime)
    return queryResultList

#If check pass, return True; else return a error message
def checkPaper(category, title, content):
    categoryValid = False
    for cat in conf.paperCategoryList:
        if cat['catValue'] == category:
            categoryValid = True
            break
    if not categoryValid:
        return '请选择正确的文章分类'
        
    if not title:
        return '没有填写文章标题'
    if len(title) < titleMinLen:
        return '文章标题太短，最少' + str(titleMinLen) + '个字'
    if len(title) > titleMaxLen:
        return '文章标题太长，最多' + str(titleMaxLen) + '个字'
    if not content:
        return '没有填写文章内容'
    if len(content) < contentMinLen:
        return '文章内容太短，最少' + str(contentMinLen) + '个字'
    if len(content) > contentMaxLen:
        return '文章内容太长，最多' + str(contentMaxLen) + '个字'
    
    return True